﻿using System;
using System.Data;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using MySql.Data.MySqlClient;
using DevExpress.Web.ASPxGridView;
using System.Globalization;

public partial class ReportView_ReportAlarm : System.Web.UI.Page
{
    //private ToolTipController toolTipController1 = new ToolTipController();
    private static Common common = new Common();
    private static string strTimeFormat = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.StartDate.Value = DateTime.Now.Date.AddDays(-1).ToString();
            this.EndDate.Value = DateTime.Now.Date.ToString();
            if (Request.QueryString["time"] != null && Request.QueryString["time"].ToString() == "d")
            {
                this.StartDate.Value = DateTime.Now.Date.AddDays(-7).ToString("yyyy/MM/dd HH:mm:ss");
                this.EndDate.Value = DateTime.Now.Date.ToString("yyyy/MM/dd HH:mm:ss");
            }
            if (Request.QueryString["connstring"] != null)
            {
                this.hidConnectString.Value = Request.QueryString["connstring"].ToString();//连接字符串
                this.hidProcedure.Value = Request.QueryString["procedure"].ToString();//存储过程名称
                this.hidReportID.Value = Request.QueryString["reportid"].ToString();//报表ID
                this.hidAbscissa.Value = Request.QueryString["x"].ToString();//横坐标名称
                GetEquipName(Request.QueryString["connstring"].ToString());
                // InitData();
            }
        }
    }
    protected void btnSelAlarm_Click(object sender, EventArgs e)
    {
        InitData();
    }
    protected void ASPxPageControl1_ActiveTabChanged(object source, DevExpress.Web.ASPxTabControl.TabControlEventArgs e)
    {
        InitData();
    }
    protected void btnXlsExport_Click(object sender, EventArgs e)
    {
        // this.gridExport.WriteXlsToResponse(WebChartControl1.Titles[0].Text);
        InitData();
        this.gridExport.WriteXlsToResponse();
    }

    #region 统计图操作
    void InitSeries()
    {
        DataSet ds = getDataSet("STAT");//统计图中出现具体详细的信息
        DataTable dt = ds.Tables[0].Copy();//将Dt复制 
        string fieldName = "ne_id";
        string x = this.hidAbscissa.Value.ToString();// "equip_name";
        string y = this.ASPxComboBoxIndicators.SelectedItem.Value.ToString();
        //bool isCheck = false;//标记是否要校验指标

        if (ASPxComboBoxEquipName.SelectedItem.Text.ToString() != "全部" && ASPxComboBoxIndicators.SelectedItem.Text.ToString() == "全部")
        {
            dt = ConvertTable(ds.Tables[0]);
            fieldName = "IndicatorsCN";
            x = this.hidAbscissa.Value.Trim();
            y = "IndicatorsValue";
            // isCheck = true;
        }

        DataTable dt1 = MySQLHelper.SelectDistinct("equip", dt, fieldName);
        DataRow[] dr;
        this.WebChartControl1.Series.Clear();//清除所有的Series
        int length = dt1.Rows.Count;
        string equipName = "";
        string[] label = new string[10];//存储要标记的点,只记录十个点
        int labelLength = 0;
        int n = 0;//记录要存储的节点的循环标记
        //string s = string.Empty;
        for (int i = 0; i < length; i++)
        {
            equipName = dt1.Rows[i][fieldName].ToString();
            //if (!isCheck )
            //{
            dr = dt.Select(fieldName + "='" + equipName + "'");
            equipName = dr[0][1].ToString();//获取设备或指标的名称
            if (!equipName.Contains("告警级别") && !equipName.Contains("统计开始时间"))
            {
                this.WebChartControl1.Series.Add(equipName, GetViewType());
                this.WebChartControl1.Series[equipName].Points.Clear();
                if (i == 0)
                {
                    ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels.Clear();
                }
                int num = dr.Length;
                labelLength = (num - 2) / 4;
                string xAxis = string.Empty;
                for (int j = 0; j < num; j++)
                {
                    try
                    {
                        try
                        {
                            xAxis = Convert.ToDateTime(dr[j][x].ToString()).ToString(strTimeFormat, DateTimeFormatInfo.InvariantInfo);
                        }
                        catch (Exception)
                        {
                            xAxis = dr[j][x].ToString();
                            //throw;
                        }
                        this.WebChartControl1.Series[equipName].Points.Add(new SeriesPoint(xAxis, dr[j][y]));
                    }
                    catch (Exception)
                    {

                        continue;
                    }
                    //if (i == 0 && labelLength > 1 &&(j==0|| j==num-1||(j%labelLength ==0)))
                    if (labelLength > 0 && i == 0 && (j % labelLength == 0))
                    {
                        //s += "i=" + i + "#j=" + j;
                        ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels.Add(new CustomAxisLabel(xAxis));
                        ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels[n++].AxisValue = xAxis;
                    }
                }
                //s += "#labelLength=" + labelLength+"$%$";
            }
        }
        if (length == 0)
        {
            this.WebChartControl1.Series.Add("", GetViewType());
        }


        WebChartControl1.Titles[0].Text = this.hidWebChartTitle.Value.ToString();
        string u = GetUnit();
        if (u != string.Empty)
        {
            ((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Text = "单位：" + u;
            ((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Visible = true;
        }

        //((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Font = System.Drawing.Font.FromHdc((IntPtr)2);

        if (ASPxComboBoxIndicators.SelectedItem.Text != "全部")
        {
            WebChartControl1.Titles[0].Text = ASPxComboBoxIndicators.SelectedItem.Text;
        }
    }
    /// <summary>
    /// 校验参数是否可见
    /// </summary>
    /// <param name="param">参数名称</param>
    /// <returns></returns>
    private bool CheckParam(string param)
    {
        int length = ASPxComboBoxIndicators.Items.Count;
        for (int i = 0; i < length; i++)
        {
            if (param == ASPxComboBoxIndicators.Items[i].Text)
            {
                return true;
            }
        }
        return false;
    }

    protected void WebChartControl1_CustomCallback(object sender, DevExpress.XtraCharts.Web.CustomCallbackEventArgs e)
    {
        InitSeries();
        if (e.Parameter == "ViewType")
        {
            PerformViewTypeAction();
        }
        else if (e.Parameter == "ShowLabels")
        {
            PerformViewTypeAction();
            SetSeriesLabel();
        }
    }
    private ViewType GetViewType()
    {
        ViewType v = ViewType.Bar;
        switch ((string)cbViewType.SelectedItem.Text)
        {
            case "曲线图":
                v = ViewType.Line;
                break;
            case "柱状图":
                v = ViewType.Bar;
                break;
            case "饼图":
                v = ViewType.Pie;
                break;
            case "3D饼图":
                v = ViewType.Pie3D;
                break;
        }
        return v;
    }
    void PerformViewTypeAction()
    {
        ViewType viewType = ViewType.Line;
        switch ((string)cbViewType.SelectedItem.Text)
        {
            case "曲线图":
                viewType = ViewType.Line;
                break;
            case "柱状图":
                viewType = ViewType.Bar;
                break;
            case "饼图":
                viewType = ViewType.Pie;
                break;
            case "3D饼图":
                viewType = ViewType.Pie3D;
                break;
        }
        foreach (Series series in WebChartControl1.Series)
        {
            series.ChangeView(viewType);
            byte transparency = 0;
            if (series.View is Area3DSeriesView || series.View is AreaSeriesView || series.View is SplineAreaSeriesView)
                transparency = 135;
            ITransparableView transparableView = series.View as ITransparableView;
            if (transparableView != null)
                transparableView.Transparency = transparency;
            UpdateSeries(series);
        }

        Diagram3D diagram = WebChartControl1.Diagram as Diagram3D;
        if (diagram != null)
        {
            diagram.ZoomPercent = 120;
            XYDiagram3D xyDiagram3D = diagram as XYDiagram3D;
            if (xyDiagram3D != null)
                UpdateAxes(xyDiagram3D.AxisX, xyDiagram3D.AxisY, WebChartControl1.Series[0].View);
        }
        else
        {
            XYDiagram xyDiagram = WebChartControl1.Diagram as XYDiagram;
            if (xyDiagram != null)
                UpdateAxes(xyDiagram.AxisX, xyDiagram.AxisY, WebChartControl1.Series[0].View);
        }
    }
    bool IsFullStackedView(SeriesViewBase view)
    {
        return
            view is FullStackedAreaSeriesView ||
            view is FullStackedArea3DSeriesView ||
            view is FullStackedSplineAreaSeriesView ||
            view is FullStackedSplineArea3DSeriesView;
    }
    void UpdateAxes(AxisBase axisX, AxisBase axisY, SeriesViewBase view)
    {
        axisX.DateTimeOptions.Format = DateTimeFormat.MonthAndDay;
        if (IsFullStackedView(view))
        {
            axisY.NumericOptions.Format = NumericFormat.Percent;
            axisY.NumericOptions.Precision = 0;
        }
        else
            axisY.NumericOptions.Format = NumericFormat.General;
    }
    void UpdateSeries(Series series)
    {
        if (IsFullStackedView(series.View))
        {
            series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
            series.PointOptions.ValueNumericOptions.Precision = 0;
        }
        else
            series.PointOptions.ValueNumericOptions.Format = NumericFormat.General;
    }
    void SetSeriesLabel()
    {
        foreach (Series series in WebChartControl1.Series)
        {
            series.Label.Visible = checkBoxShowLabel.Checked;
            //series.PointOptions.PointView = PointView.ArgumentAndValues; SeriesLabelBase.ResolveOverlappingMode 
        }
    }
    public void chartControl1_CustomDrawSeriesPoint(object sender, CustomDrawSeriesPointEventArgs e)
    {
        //e.LabelText = e.Series + "\r\n" + e.SeriesPoint.ArgumentSerializable + "\r\n值：" + e.SeriesPoint.ValuesSerializable;
        e.LabelText = e.SeriesPoint.ArgumentSerializable + " 值:" + e.SeriesPoint.ValuesSerializable;
    }
    #endregion

    #region 初始化界面
    /// <summary>
    /// 获取指标数据集
    /// </summary>
    /// <param name="conn">数据库连接字符串</param>
    /// <param name="reportid">报表类型ID</param>
    private DataSet GetIndicatorsData(string conn, int reportid)
    {
        CommandType commtype = CommandType.StoredProcedure;
        //存储过程参数
        MySqlParameter[] mySqlPar = new MySqlParameter[1];
        mySqlPar[0] = new MySqlParameter("reporttype", MySqlDbType.Int32);
        mySqlPar[0].Value = reportid;
        //调用函数执行存储过程
        return MySQLHelper.ExecuteDataset(conn, commtype, "report_get_map", mySqlPar);
    }
    /// <summary>
    /// 获取设备名称
    /// </summary>
    /// <param name="reportType">设备类型(dxt表示交换机，tbs表示基站)</param>
    /// <param name="conn">连接数据库的字符串</param>
    private void GetEquipName(string conn)
    {
        //根据传入的参数判断报表类型是交换机还是基站
        string procedureName = "select * from c_unicom_gui.view_ne_all";
        int index = 0;
        CommandType commtype = CommandType.Text;
        //调用函数执行存储过程
        DataSet ds = MySQLHelper.ExecuteDataset(conn, commtype, procedureName);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            int length = ds.Tables[0].Rows.Count;
            ASPxComboBoxEquipName.Items.Clear();
            ASPxComboBoxEquipName.Items.Add("全部", "");
            for (int i = 0; i < length; i++)
            {
                ASPxComboBoxEquipName.Items.Add(ds.Tables[0].Rows[i]["CHINA_NAME"].ToString(), ds.Tables[0].Rows[i]["NE_ID"].ToString());
            }
            ASPxComboBoxEquipName.SelectedIndex = 0;
            tdIndicators.Attributes["class"] = "visa";//将指标下拉框设置可见
            GetIndicators(conn, Convert.ToInt32(this.hidReportID.Value.ToString()), index);
        }
        else
        {
            ASPxComboBoxEquipName.Visible = false;//将设备下拉框设置不可见
            //tdIndicators.Attributes["class"] = "unvisable";//将指标下拉框设置不可见
        }
    }
    /// <summary>
    /// 初始化指标下拉框
    /// </summary>
    /// <param name="conn">数据库连接字符串</param>
    /// <param name="reportid">报表类型ID</param>
    /// <param name="selectIndex">下拉框选中Index</param>
    private void GetIndicators(string conn, int reportid, int selectIndex)
    {
        string title = string.Empty;
        string tablename = string.Empty;
        string value = string.Empty;
        string text = string.Empty;
        switch (reportid)
        {
            case 205:
                tablename = "c_unicom_gui.alarmlevel";
                value = "LEVEL_ENNAME";
                text = "LEVEL_CNNAME";
                title = "告警级别";
                break;
            case 206:
                tablename = "c_unicom_gui.asaptemplate";
                value = "CAUSENO";
                text = "CN_CAUSEEXPLAIN";
                title = "告警原因";
                break;
            default:
                tablename = "c_unicom_gui.asaptemplate";
                value = "CAUSENO";
                text = "CN_CAUSEEXPLAIN";
                title = "告警原因";
                break;
        }
        DataSet ds = MySQLHelper.ExecuteDataset(conn, CommandType.Text, "select * from " + tablename);// GetIndicatorsData(conn, reportid);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            int length = ds.Tables[0].Rows.Count;
            ASPxComboBoxIndicators.Items.Clear();
            ASPxComboBoxIndicators.Items.Add("全部", "");
            for (int i = 0; i < length; i++)
            {
                ASPxComboBoxIndicators.Items.Add(ds.Tables[0].Rows[i][text].ToString(), ds.Tables[0].Rows[i][value].ToString());
                //  hidUnits.Value += ds.Tables[0].Rows[i]["UNITS"].ToString() + "#";
            }
            ASPxComboBoxIndicators.SelectedIndex = selectIndex;
            //ASPxComboBoxIndicators.SelectedItem.Value.ToString();//选中的值
            InitGridView(conn, reportid);
        }
        this.hidWebChartTitle.Value = title;
        WebChartControl1.Titles[0].Text = title;
        bLabel.InnerText = title;
        this.tdIndicator.InnerText = title;
    }
    private void InitGridView(string conn, int reportid)
    {
        DataSet ds = GetIndicatorsData(conn, reportid);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            int length = ds.Tables[0].Rows.Count;
            GridViewDataTextColumn col1 = new GridViewDataTextColumn();
            col1.FieldName = "china_name";
            col1.Caption = "告警对象 ";
            Grid.Columns.Add(col1);
            for (int i = 0; i < length; i++)
            {
                GridViewDataTextColumn col = new GridViewDataTextColumn();
                col.FieldName = ds.Tables[0].Rows[i]["EN_TARGET_NAME"].ToString();
                col.Caption = ds.Tables[0].Rows[i]["CN_TARGET_NAME"].ToString();
                Grid.Columns.Add(col);
            }
        }

        // Grid.Columns.Add();
    }
    #endregion

    #region 公共操作
    /// <summary>
    /// 调用存储过程
    /// </summary>
    /// <param name="type">存储过程类型，ALL(返回所有数据),STAT(返回统计值),PARTICULAR(返回详细值)</param>
    /// <returns></returns>
    public DataSet getDataSet(string type)
    {
        // DataSet ds = MySQLHelper.ExecuteDataset(this.hidConnectString.Value.Trim(), commtype, this.hidProcedure.Value.Trim(), mySqlPar);
        string[,] str = new string[5, 2] { { "p_ne_id", "string" }, { "p_alarmlevel", "string" }, { "p_stime", "datetime" }, { "p_etime", "datetime" }, { "p_is_total", "string" } };
        string[] v = new string[] { ASPxComboBoxEquipName.SelectedItem.Value.ToString(), ASPxComboBoxIndicators.SelectedItem.Value.ToString(), this.StartDate.Value, this.EndDate.Value, type.ToUpper() };
        strTimeFormat = common.GetTimeFormat(this.StartDate.Value, this.EndDate.Value);
        return common.GetList(this.hidProcedure.Value.Trim(), str, v);
    }
    //加载数据
    private void InitData()
    {
        if (ASPxPageControl1.ActiveTabIndex == 1)
        {
            DataSet ds = getDataSet("ALL");
            this.Grid.DataSource = ds;//表格中将所有的数据都显示出来
            this.Grid.DataBind();
        }
        else
        {
            InitSeries();
            SetSeriesLabel();
        }
    }
    protected void Grid_PageIndexChanged(object sender, EventArgs e)
    {
        this.Grid.DataSource = getDataSet("ALL");//表格中将所有的数据都显示出来
        this.Grid.DataBind();
    }
    /// <summary>
    /// 转换数据，将数据集列行转换
    /// </summary>
    /// <param name="dt">原数据集</param>
    /// <returns></returns>
    private DataTable ConvertTable(DataTable dt)
    {
        DataTable dtNew = GetTable();
        try
        {
            int rCount = dt.Rows.Count;//行数
            // int cCount = dt.Columns.Count;//列数           

            DataSet ds = GetIndicatorsData(this.hidConnectString.Value.Trim(), Convert.ToInt32(this.hidReportID.Value.Trim()));
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                int length = ds.Tables[0].Rows.Count;
                for (int i = 0; i < length; i++)
                {
                    for (int k = 0; k < rCount; k++)
                    {
                        DataRow dr = dtNew.NewRow();
                        dr[0] = dt.Rows[k][this.hidAbscissa.Value.Trim()].ToString();
                        dr[1] = ds.Tables[0].Rows[i][2].ToString();
                        dr[2] = ds.Tables[0].Rows[i][3].ToString();
                        dr[3] = dt.Rows[k][ds.Tables[0].Rows[i][3].ToString()].ToString();
                        dtNew.Rows.Add(dr);
                    }
                }
            }
        }
        catch (Exception e)
        {

        }
        return dtNew;
    }
    /// <summary>
    /// 创建转换表
    /// </summary>
    /// <returns></returns>
    private DataTable GetTable()
    {
        return common.GetTable(this.hidAbscissa.Value.Trim());
    }
    private string GetUnit()
    {
        return common.GetUnit(hidUnits.Value, ASPxComboBoxIndicators.SelectedIndex.ToString());
    }
    #endregion
}
